package com.activitycode.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.activitycode.tools.imagecache.ImageTools;
import com.activitycode.tools.imagetools.ImageBuild;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;


public class ImageChooseTools{
	public static final int PHOTO_WITH_CAMERA = 116;	
	public static final int CHOOSE_PICTURE = 117;
	public static final int PHOTO_PICKED_WITH_CROP = 118;
	/**拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/com.duostec.zhuyue.pets/cache/tamp/");
	private static final String imagePath = Environment.getExternalStorageDirectory() + "/com.duostec.zhuyue.pets/cache/tamp/";
	private static Uri imageUri;
	private static String imageUrl = "";
	
	/** 拍照获取多张相片 **/
	public static void doTakePhotos(Activity context) {
		// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
		Intent intent = new Intent();
		// intent.setType("image/*"); // 开启Pictures画面Type设定为image
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); // 使用Intent.ACTION_GET_CONTENT这个Action

		intent.putExtra("return-data", true); // 有返回值
		imageUrl = imagePath+"/"+System.currentTimeMillis()+"image2.jpg";
		imageUri = Uri.fromFile(new File(imageUrl));
		// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// 直接使用，没有缩小
		context.startActivityForResult(intent, PHOTO_WITH_CAMERA); // 用户点击了从相机获取
		Log.i("MineInfActivity", "intent="+intent);
	}
	/**
	 * 获取拍照的照片路径
	 * @param context
	 * @return
	 */
	public static String getTakePhotosUrl(Activity context) {
		
		return imageUrl;
	}
	/**
	 * 获取拍照按比例压缩后的照片路径
	 * @param context
	 * @return
	 */
	public static String getTakePhotoScaleUrl(Activity context) {
		String img = saveScaleImage(imageUrl);
		return img;
	}
	
	/** 拍照获取相片 **/
	public static void doTakePhoto(Activity context) {
		// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
		Intent intent = new Intent();
		// intent.setType("image/*"); // 开启Pictures画面Type设定为image
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); // 使用Intent.ACTION_GET_CONTENT这个Action

		intent.putExtra("return-data", true); // 有返回值
		imageUrl = imagePath+"/"+"image2.jpg";
		imageUri = Uri.fromFile(new File(imageUrl));
		// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// 直接使用，没有缩小
		context.startActivityForResult(intent, PHOTO_WITH_CAMERA); // 用户点击了从相机获取
		Log.i("MineInfActivity", "intent="+intent);
	}

	/** 从相册获取图片 **/
	public static void doGalleryPhoto(Activity context) {

		Intent openAlbumIntent = doPickPhotoFromGallery();
		// openAlbumIntent.setType("image/*");
		context.startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
	}
	
	/** 从相册获取图片 **/

	public static Intent doPickPhotoFromGallery() {

		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_GET_CONTENT); // 使用Intent.ACTION_GET_CONTENT这个Action
		intent.setType("image/*"); // 获取任意图片类型
		intent.putExtra("return-data", true); // 有返回值
		return intent;

	}
	/**
     * 裁剪图片
     * @param data
     */
	public static void doCropPhoto(Activity context,Uri data,Boolean isRate){
        Intent intent = getCropImageIntent(data,isRate);
        context.startActivityForResult(intent, PHOTO_PICKED_WITH_CROP);
    }
   
    public static Intent getCropImageIntent(Uri uri,Boolean isRate) {
    	 Intent intent = new Intent("com.android.camera.action.CROP");
		   intent.setDataAndType(uri, "image/*");
		   
		   if(isRate){
			   
			   
		   }
		   intent.putExtra("crop", "true");//可裁剪
		   intent.putExtra("aspectX", 1);
		   intent.putExtra("aspectY", 1);
		   intent.putExtra("outputX", 150);
		   intent.putExtra("outputY", 150);  
		   intent.putExtra("scale", true);
		   
//		   intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		   intent.putExtra("return-data", true);//若为false则表示不返回数据
		   intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		   intent.putExtra("noFaceDetection", true); 
		   return intent;
    }
    /**
     * 获取照片的Uri
     * @param context
     * @param data
     * @return
     */
    public static Uri getGalleryUri(Activity context, Intent data){
    	ContentResolver resolver = context.getContentResolver();
		Log.i("resolver********************", "" + resolver);
		// 照片的原始资源地址ַ
		Uri originalUri = data.getData();
		return originalUri;
    }
    /**
     * 获取照相的Uri
     * @return
     */
    public static Uri getTakeUri(){
    	
		return imageUri;
    }
    /**
     * 获取裁剪后的bitmap
     * @param data
     * @return
     */
    public static Bitmap getCropBitmap(Intent data){
    	
    	return data.getParcelableExtra("data");
    }
    
    /**  
	* 读取路径中的图片，然后将其转化为缩放后的bitmap  
	*   
	* @param path  
	*/  
	public static String saveScaleImage(String path) {   
		String fileSavePath ="";
		long time = System.currentTimeMillis();
		if(sdCardExist()){
			return "";
		}		
		fileSavePath = imagePath+time+".jpg";
		File folder = new File(imagePath);
		if(!folder.exists()){
			folder.mkdirs();
		}		
		BitmapFactory.Options options = new BitmapFactory.Options();   
		options.inJustDecodeBounds = true;   
		// 获取这个图片的宽和高   
		int width = options.outWidth;
		int height = options.outHeight;
		float targetW = 480;
		float targetH = 800;
		Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回bm为空   
		options.inJustDecodeBounds = false;   
		// 计算缩放比   
		if(width>height){
			targetW = 800;
			targetH = 480;
		}
		int be1 = (int) (width/targetW);
		int be2 = (int) (height/targetH);
		int be = be1;
		if(be1<be2){
			be = be2;
		}	 
		if (be <= 0){
			be = 1;  
		}else{
			if(be<=1){
				be = 1; 
			}else if(be<=2&&be>1){
				be = 2;
			}
		}			 
		options.inSampleSize =be; // 图片长宽各缩小二分之一   
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦   
		bitmap = BitmapFactory.decodeFile(path, options); 
		if(bitmap==null){
			Log.i("Result", "kongpath1="+path);
			return "";
		} 
		// savePNG_After(bitmap,path);   
		if(saveJPGE_After(bitmap,100, fileSavePath)){
			if(!bitmap.isRecycled()){
				bitmap.recycle();
			}
			bitmap=null;
			return fileSavePath;
		}else{
			if(!bitmap.isRecycled()){
				bitmap.recycle();
			}
			bitmap=null;
			return "";
		}

	}
	
	/**
	 * 获取sd卡路径
	 * @return
	 */
	public static String getSDPath(){
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState()
		.equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
		if (sdCardExist)
		{
			sdDir = Environment.getExternalStorageDirectory();//获取跟目录
		}
		return sdDir.toString();
	}

	//	Android中判断SD卡是否存在，并且可以进行写操作，可以使用如下代码
	public static Boolean sdCardExist(){
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
			{
			//TODO:
		    return true;
			}else{
				return false;
			}

	}

	/**  
	* 保存图片为JPEG  
	*   
	* @param bitmap  
	* @param path  
	*/  
	public static Boolean saveJPGE_After(Bitmap bitmap, int arg,String path) { 
		File photoFile = new File(path);   
		try {   
			FileOutputStream out = new FileOutputStream(photoFile);  
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, arg, out)) { //0<=arg<=100,yasuolv  
				out.flush();   
				out.close();   
			}   
		} catch (FileNotFoundException e) {  
			photoFile.delete();
			e.printStackTrace();  
			Log.i("tupin", "filenotfound="+e);
		} catch (IOException e) {  
			photoFile.delete();
			e.printStackTrace();   
			Log.i("tupin", "io="+e);
		}catch (Exception e){
			e.printStackTrace();   
			Log.i("tupin", "exception="+e);
		}
		return true;
	}  
    
}